﻿using DG.Tweening;
using DTFramework.Util;
using Newtonsoft.Json.Linq;
using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace DTFramework.UI
{
    public class UILoginForm : MonoBehaviour
    {
        [SerializeField] TMP_InputField m_InputAccount;
        [SerializeField] TMP_InputField m_InputPassword;
        [SerializeField] Button m_Login;
        [SerializeField] Button m_Exit;
        [SerializeField] Toggle m_TogRemember;
        [SerializeField] TextMeshProUGUI m_TextErrorTip;

        private string m_LoginUrl;
        /// <summary>
        /// 登录结果
        /// </summary>
        public Action<bool, string> OnLoginResult;

        /// <summary>
        /// 登录账号密码
        /// </summary>
        public static string Account { get; private set; }
        public static string Password { get; private set; }

        public void Init(string loginUrl)
        {
            m_LoginUrl = loginUrl;

            VerifyInfo();
            //
            m_Login.onClick.AddListener(OnLoginClick);
            m_Exit.onClick.AddListener(() => GameEntry.ApplicationQuit());
            m_InputAccount.onValueChanged.AddListener(text => m_InputAccount.text = text.TrimStart().TrimEnd());
            m_InputPassword.onValueChanged.AddListener(text => m_InputPassword.text = text.TrimStart().TrimEnd());
        }
        private void OnDestroy()
        {
            m_Login.onClick.RemoveListener(OnLoginClick);
        }
        //信息认证
        private void VerifyInfo()
        {
            if (PlayerPrefs.GetInt("isRemember") == 1)
            {
                var projectID = Application.productName + Application.version;
                if (PlayerPrefs.GetString("projectID") == projectID)
                {
                    var rememberTimeStr = PlayerPrefs.GetString("rememberTime");
                    if (DateTime.TryParse(rememberTimeStr, out DateTime rememberTime))
                    {
                        if (rememberTime > DateTime.Now)
                        {
                            m_InputAccount.text = PlayerPrefs.GetString("account");
                            m_InputPassword.text = PlayerPrefs.GetString("password");
                            m_TogRemember.isOn = true;
                            return;
                        }
                    }
                }
                m_InputAccount.text = null;
                m_InputPassword.text = null;
                m_TogRemember.isOn = false;
            }
        }

        //   登录
        private async void OnLoginClick()
        {
            var jObject = new JObject();
            jObject.Add("username", m_InputAccount.text);
            var password = EncryptUtil.Md5Encrypt32(m_InputPassword.text);
            jObject.Add("password", password);
            Account = m_InputAccount.text;
            Password = password;
            try
            {
                var result = await GameEntry.WebRequest.RequestPost(m_LoginUrl, jObject);
                if (result == null)
                {
                    LoginFailure($"登陆失败，请检查账号密码！");
                    OnLoginResult?.Invoke(false, null);
                    return;
                }
                var jsonObj = JObject.Parse(result);
                if (jsonObj.TryGetValue("success", out JToken value))
                {
                    if (value.ToObject<bool>())
                    {
                        var token = jsonObj["data"]["accessToken"].ToString(); Debug.Log(token);
                        LoginSucess(token);
                    }
                    else//认证失败
                    {
                        LoginFailure($"登陆失败，{jsonObj["msg"]}！");
                        OnLoginResult?.Invoke(false, null);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                LoginFailure($"登陆失败，请检查账号密码！");
                OnLoginResult?.Invoke(false, null);
            }
            // var result = await GameEntry.WebRequest.RequestPost(m_LoginUrl, jObject);
            // if (result == null)
            // {
            //     LoginFailure($"登陆失败，请检查账号密码！");
            //     OnLoginResult?.Invoke(false, null);
            //     return;
            // }
            // var jsonObj = JObject.Parse(result);
            // if (jsonObj.TryGetValue("success", out JToken value))
            // {
            //     if (value.ToObject<bool>())
            //     {
            //         var token = jsonObj["data"]["accessToken"].ToString(); Debug.Log(token);
            //         LoginSucess(token);
            //     }
            //     else//认证失败
            //     {
            //         LoginFailure($"登陆失败，{jsonObj["msg"]}！");
            //         OnLoginResult?.Invoke(false, null);
            //     }
            // }
        }
        //登录成功
        private void LoginSucess(string token)
        {
            OnRemember(m_TogRemember.isOn);
            OnLoginResult?.Invoke(true, token);
            Destroy(this.gameObject, 0.1f);
        }
        //登录失败弹窗
        private void LoginFailure(string content)
        {
            if(m_TextErrorTip == null) return;
            m_TextErrorTip.gameObject.SetActive(true);
            m_TextErrorTip.text = content;
            DOTween.To(() => m_TextErrorTip.color, x => m_TextErrorTip.color = x, new Color(1, 0, 0, 0.4f), 1f)
                .SetLoops(2, LoopType.Yoyo)
                .OnComplete(() => m_TextErrorTip.gameObject.SetActive(false))
                .SetAutoKill();
        }
        //记住密码
        private void OnRemember(bool isOn)
        {
            if (isOn)
            {
                if (!string.IsNullOrEmpty(m_InputAccount.text) && !string.IsNullOrEmpty(m_InputPassword.text))
                {
                    PlayerPrefs.SetString("account", m_InputAccount.text);
                    PlayerPrefs.SetString("password", m_InputPassword.text);
                    PlayerPrefs.SetInt("isRemember", 1);
                    PlayerPrefs.SetString("rememberTime", DateTime.Now.AddDays(7).ToString());
                    var projectID = Application.productName + Application.version;
                    PlayerPrefs.SetString("projectID", projectID);
                }
            }
            else
            {
                m_InputAccount.text = null;
                m_InputPassword.text = null;
                PlayerPrefs.SetString("account", null);
                PlayerPrefs.SetString("password", null);
                PlayerPrefs.SetInt("isRemember", 0);
                PlayerPrefs.SetString("rememberTime", null);
                PlayerPrefs.SetString("projectID", null);
            }
        }
    }
}